//
//  SEGOrderMessageViewController.m
//  ExcellentHome
//
//  Created by Andy on 16/5/31.
//  Copyright © 2016年 陈区. All rights reserved.
//

//#import "HS_MoneyBackViewController.h"
//#import "HS_OrderViewController.h"
//#import "OrderComfirmViewController.h"

#import "SEGOrderMessageViewController.h"

#import "BaseButtonView.h"
#import "NewMessageTabelViewCell.h"

#import "SEGOrderMessageViewModel.h"

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif

#import <Commom/ImageEnarge.h>

@interface SEGOrderMessageViewController () <UITableViewDelegate, UITableViewDataSource, UITextViewDelegate,  UINavigationControllerDelegate, UIActionSheetDelegate, SEGImagePickerManagerDelegate> {
    // 键盘偏移量
    CGSize kbSize;
}

/// 文本框的frame
@property (nonatomic, assign) CGRect footerViewFrame;;
/// 输入框
@property (nonatomic, strong) UIImageView *footerImageView;
/// 输入消息的文本框
@property (nonatomic, strong) UITextView *footerTextView;
/// 照片按钮
@property (nonatomic, strong) CustomButtonView *upImageBtn;
/// 客服按钮
@property (nonatomic, strong) CustomButtonView *serviceBtn;
/// 自定义cell
@property (nonatomic, strong) NewMessageTabelViewCell *messageCell;
/// 表格
@property (nonatomic, strong) UITableView *tableView;
/// 实现简单图片放大的类
@property (nonatomic, strong) ImageEnarge *baseEnarge;
/// 相机, 相册
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;

/// viewModel
@property (nonatomic, strong) SEGOrderMessageViewModel *viewModel;

@end

@implementation SEGOrderMessageViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    [self scrollTableToFoot];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.footerTextView resignFirstResponder];
    [UIView setAnimationDuration:0.3];
    self.footerImageView.frame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerTextView.frame = CGRectMake(50, 8, self.view.frame.size.width - 98, 33);
    CGRect newFrame = self.tableView.frame;
    newFrame.size.height = self.footerViewFrame.origin.y;
    self.tableView.frame = newFrame;
    [UIView commitAnimations];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    @weakify(self);
    // 获取消息接口数据
    [SVProgressHUD show];
    [[self.viewModel.msgV3Command execute:self.groupID] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SVProgressHUD dismiss];
        self.messageCell = [NewMessageTabelViewCell new];
        [self.tableView reloadData];
        [self scrollTableToFoot];
    }];
 
    //获取服务商详情
    [SVProgressHUD show];
    [[self.viewModel.providerCommand execute:self.groupID] subscribeNext:^(NSString *title) {
        @strongify(self);
        [SVProgressHUD dismiss];
        if (self.title.length == 0 && title.length > 0) self.title = title;
    }];
    
    // 监听通知
    [self seg_initNotification];

    // UI
    CGRect appbounds = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight() - 44 - 20);
    self.footerViewFrame = CGRectMake(0, appbounds.size.height - 49, appbounds.size.width, 49);
    [self.view addSubview:self.footerImageView];
    [self.footerImageView addSubview:self.footerTextView];
    [self.footerImageView addSubview:self.upImageBtn];
    [self.footerImageView addSubview:self.serviceBtn];
}

#pragma mark - Load Data
/// 上传信息的方法
- (void)pushMessagesForChat:(NSString*)msgType contentType:(NSString*)contentType userId:(NSString*)userId title:(NSString*)title description:(NSString*)description content:(NSString*)content type:(NSString*)type serviceId:(NSString*)serviceId from:(NSString*)from groupId:(NSString*)groupId provider:(NSString*)provider {
    int msg = [msgType intValue];
    int cot = [contentType intValue];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:msg], @"msgType", [NSNumber numberWithInt:cot], @"contentType", userId, @"userId", self.viewModel.headerImageUrl, @"title", description, @"description", content, @"content", type, @"type", serviceId, @"serviceId", from, @"from", groupId, @"groupId", provider, @"provider", self.viewModel.headerImageUrl, @"providerIcon",kAccountUserID,@"providerSid", nil];
    
    @weakify(self);
    [SVProgressHUD show];
    [[self.viewModel.sendMsgCommand execute:RACTuplePack(dic, self.groupID)] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SVProgressHUD dismiss];
        [self.tableView reloadData];
        [self scrollTableToFoot];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - Init
// 初始化通知
- (void)seg_initNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillHideNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onReceiveMessageNotification:)
                                                 name:RECEIVE_MESSAGE_UI
                                               object:nil];
}

#pragma mark - 滚动到最后或最前面一行
//滚动表格到最后一行
- (void)scrollTableToFoot {
    NSInteger s = [self.tableView numberOfSections];
    if (s < 1) return;
    NSInteger r = [self.tableView numberOfRowsInSection:s - 1];
    if (r < 1) return;
    NSIndexPath* ip = [NSIndexPath indexPathForRow:r - 1 inSection:s - 1];
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
//滚动表格到第一行
- (void)scrollTableToTop {
    NSInteger s = [self.tableView numberOfSections];
    if (s < 1) return;
    NSInteger r = [self.tableView numberOfRowsInSection:0];
    if (r < 1) return;
    NSIndexPath* ip = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - Event
// 打电话
- (void)telPhont {
    if ([self.viewModel.tel length] > 0) {
        NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"tel:%@", self.viewModel.tel];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}
// 添加图片
- (void)addPicBtnAction:(UIButton *)sender {
    [self.footerTextView resignFirstResponder];
    [UIView setAnimationDuration:0.3];
    self.footerImageView.frame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerTextView.frame = CGRectMake(50, 8, self.view.frame.size.width - 98, 33);

    CGRect newFrame = self.tableView.frame;
    newFrame.size.height = self.footerViewFrame.origin.y;
    self.tableView.frame = newFrame;
    [UIView commitAnimations];

    [self.view endEditing:YES];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机选择",@"相机",nil];
    //    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];//解决最后一项点击失效问题
    [actionSheet showFromTabBar:self.navigationController.tabBarController.tabBar];
}
// 发送按钮点击
- (void)btnSendMsgClicked:(UIButton *)sender {
    if (![self.footerTextView.text isEqualToString:@""]) {
        NSString* temp = [self.footerTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (temp.length == 0) return;
        
        [self.footerTextView resignFirstResponder];
        [self sendMessageForString];

        self.footerTextView.text = @"";

        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        self.footerImageView.frame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
        self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
        self.footerTextView.frame = CGRectMake(50, 8, self.view.frame.size.width - 98, 33);

        CGRect newFrame = self.tableView.frame;
        newFrame.size.height = self.footerViewFrame.origin.y;
        self.tableView.frame = newFrame;
        [UIView commitAnimations];
    }
    [self performSelector:@selector(scrollTableToFoot) withObject:nil afterDelay:0.1];
}
//发送消息
- (void)sendMessageForString {
    NSArray* arr = [self.groupID componentsSeparatedByString:@"|"];
    [self pushMessagesForChat:@"0" contentType:@"1" userId:arr[1] title:kAccountNickName description:self.footerTextView.text content:self.footerTextView.text type:kMessageTypeHomeService serviceId:arr[2] from:@"1" groupId:self.groupID provider:self.viewModel.providerName];
}
#pragma mark - 点击聊天信息的响应
- (void)onNewMessage:(BaseButtonView *)sender {
    [self.footerTextView resignFirstResponder];
    [UIView setAnimationDuration:0.3];
    self.footerImageView.frame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerTextView.frame = CGRectMake(50, 8, self.view.frame.size.width - 98, 33);

    CGRect newFrame = self.tableView.frame;
    newFrame.size.height = self.footerViewFrame.origin.y;
    self.tableView.frame = newFrame;
    [UIView commitAnimations];

    //    MessageEntity *message = sender.tempData;
    MessageModel* message = sender.tempData;

    if ([message.contenttype isEqualToString:@"2"]) {
        [self.baseEnarge imageEnarge:[NSString stringWithFormat:@"%@%@", kClientImageRootURL, message.message]];
        
    }
    else {
        if (![ValueToString(message.turnType) isEqualToString:@"0"]) {
            NSDictionary *params = @{@"orderSid":message.objectid};
            UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initHS_OrderViewController:params];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
    }
}

#pragma mark - NSNotificationCenter (键盘监听)
- (void)onKeyboardWillHideNotification:(NSNotification *)aNotification {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];

    self.footerImageView.frame = self.footerViewFrame;
    CGRect newFrame = self.tableView.frame;
    newFrame.size.height = self.footerViewFrame.origin.y;
    self.tableView.frame = newFrame;

    [UIView commitAnimations];
}

- (void)onKeyboardWillShowNotification:(NSNotification*)aNotification {
    kbSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];

    //底框上移
    //表格高度减小
    CGRect newFrame = self.footerViewFrame;
    newFrame.origin.y -= kbSize.height;
    self.footerImageView.frame = newFrame;

    CGRect newTableViewFrame = self.tableView.frame;
    newTableViewFrame.size.height = newFrame.origin.y;
    self.tableView.frame = newTableViewFrame;

    [self scrollTableToFoot];

    [UIView commitAnimations];
}
// 接收到消息
- (void)onReceiveMessageNotification:(NSNotification *)aNotification {
    @weakify(self);
    [[self.viewModel.receiveCommand execute:self.groupID] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.tableView reloadData];
        [self performSelector:@selector(scrollTableToFoot) withObject:nil afterDelay:0.1];
    }];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView*)textView {
    CGSize size = STRING_SIZE_FONT(self.view.frame.size.width - 83, textView.text, 14);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    if (size.height < 33) {
        self.footerImageView.frame = CGRectMake(0, self.view.frame.size.height - kbSize.height - 49, self.footerImageView.frame.size.width, 49);
        self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 49, self.footerTextView.frame.size.width, 49);
        self.footerTextView.frame = CGRectMake(50, 8, self.view.frame.size.width - 98, 33);
    } else {
        self.footerTextView.frame = CGRectMake(50, self.view.frame.size.height - kbSize.height - 32 - size.height, self.footerImageView.frame.size.width, size.height + 32);
        self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 32 - size.height, self.footerImageView.frame.size.width, size.height + 32);
        self.footerTextView.frame = CGRectMake(50, 8, self.view.frame.size.width - 98, size.height + 16);
    }
    [UIView commitAnimations];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text  {
    if ([text isEqualToString:@"\n"]) { //点击发送按钮
        [self btnSendMsgClicked:nil];
        return NO;
    }
    return YES;
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0: //从手机相册选择
        {
            self.imagePicker = [[SEGImagePickerManager alloc] init];
            self.imagePicker.delegate = self;
            self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
            self.imagePicker.allowsEditing = NO;
            self.imagePicker.maxImagesCount = 3;
            [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
            break;
        }
        case 1: //相机
        {
            self.imagePicker = [[SEGImagePickerManager alloc] init];
            self.imagePicker.delegate = self;
            self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
            self.imagePicker.allowsEditing = NO;
            [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
            break;
        }
        default:
            break;
    }
}

#pragma mark - SEGImagePickerManagerDelegate
- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager
        didFinishPickingPhotos:(NSArray<UIImage *> *)photos
                        assets:(NSArray<PHAsset *> *)assets
         isSelectOriginalPhoto:(BOOL)isSelect {
    @weakify(self);
    [SVProgressHUD show];
    [[self.viewModel.upLoadImgCommand execute:photos] subscribeNext:^(NSArray *data) {
        @strongify(self);
        [SVProgressHUD dismiss];
        NSString *urlString = [data componentsJoinedByString:@","];
        NSArray *arr = [self.groupID componentsSeparatedByString:@"|"];
        // 发送消息
        [self pushMessagesForChat:@"0" contentType:@"2" userId:arr[2] title:kAccountNickName description:urlString content:urlString type:kMessageTypeHomeService serviceId:arr[1] from:@"1" groupId:self.groupID provider:self.viewModel.providerName];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.footerTextView resignFirstResponder];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    self.footerImageView.frame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerViewFrame = CGRectMake(0, self.view.frame.size.height - 49, self.footerImageView.frame.size.width, 49);
    self.footerTextView.frame = CGRectMake(50, 8, self.view.frame.size.width - 98, 33);

    CGRect newFrame = self.tableView.frame;
    newFrame.size.height = self.footerViewFrame.origin.y;
    self.tableView.frame = newFrame;
    [UIView commitAnimations];
}
#pragma - mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.resultArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.messageCell cellHight:self.viewModel.resultArray[indexPath.row]];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* identity = @"cellstr1";
    NewMessageTabelViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identity];
    if (cell == nil) {
        cell = [[NewMessageTabelViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identity];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        /**<点击按钮*/
        CustomButtonView* clickBtn = [[CustomButtonView alloc] init];
        clickBtn.tag = 1003;

        [clickBtn addTarget:self action:@selector(onNewMessage:) forControlEvents:UIControlEventTouchUpInside];
        [cell.content addSubview:clickBtn];
    }
    NSDictionary* dict = self.viewModel.resultArray[indexPath.row];

    [cell onRequestList:dict];
    
    BaseButtonView* clickBtn = (BaseButtonView*)[cell.content viewWithTag:1003];
    clickBtn.tempData = dict;
    clickBtn.frame = CGRectMake(0, 0, CGRectGetWidth(cell.content.bounds), CGRectGetHeight(cell.content.bounds));
    return cell;
}
#pragma mark - TableViewDataSource
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section {
    return 22;
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight - 49) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UIImageView *)footerImageView {
    if (!_footerImageView) {
        _footerImageView = [[UIImageView alloc] initWithFrame:self.footerViewFrame];
        _footerImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"common_bg_input_and_cammera")];
        _footerImageView.userInteractionEnabled = YES;
    }
    return _footerImageView;
}
- (UITextView *)footerTextView {
    if (!_footerTextView) {
        _footerTextView = [[UITextView alloc] initWithFrame:CGRectMake(50, 8, LYScreenWidth() - 98, 33)];
        _footerTextView.delegate = self;
        [_footerTextView setUserInteractionEnabled:YES];
        _footerTextView.font = kFont_14;
        _footerTextView.textColor = kColor_2;
        _footerTextView.scrollEnabled = NO;
        _footerTextView.layer.cornerRadius = 5;
        _footerTextView.layer.borderColor = kColor_L2.CGColor;
        _footerTextView.layer.borderWidth = 1;
        _footerTextView.returnKeyType = UIReturnKeySend;
    }
    return _footerTextView;
}
- (CustomButtonView *)upImageBtn {
    if (!_upImageBtn) {
        _upImageBtn = [[CustomButtonView alloc] init];
        _upImageBtn.frame = CGRectMake(LYScreenWidth() - 47, 2, 45, 45);
        [self createButton:_upImageBtn btnTitle:@"照片" btnImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_pic_m")]];
        [_upImageBtn addTarget:self
                        action:@selector(addPicBtnAction:)
              forControlEvents:UIControlEventTouchUpInside];
    }
    return _upImageBtn;
}
- (CustomButtonView *)serviceBtn {
    if (!_serviceBtn) {
        _serviceBtn = [[CustomButtonView alloc] init];
        _serviceBtn.frame = CGRectMake(0, 0, 45, 45);
        [self createButton:_serviceBtn btnTitle:@"客服" btnImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_kefu_s")]];
        [_serviceBtn addTarget:self
                        action:@selector(telPhont)
              forControlEvents:UIControlEventTouchUpInside];
    }
    return _serviceBtn;
}
//设置按钮上图片与文字的相对位置
- (void)createButton:(CustomButtonView *)btn btnTitle:(NSString *)title btnImage:(UIImage *)image {
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:kColor_3 forState:UIControlStateNormal];
    [btn setImage:image forState:UIControlStateNormal];
    btn.titleLabel.font = kFont_10;
    btn.imageEdgeInsets = UIEdgeInsetsMake(-btn.titleLabel.bounds.size.height - 10, 10, btn.titleLabel.bounds.size.height, -10);
    btn.titleEdgeInsets = UIEdgeInsetsMake(btn.imageView.bounds.size.height - 10, -9, -btn.imageView.bounds.size.height, 9);
}
- (ImageEnarge *)baseEnarge {
    if (!_baseEnarge) _baseEnarge = [ImageEnarge new];
    return _baseEnarge;
}
- (SEGOrderMessageViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGOrderMessageViewModel alloc] init];
    return _viewModel;
}

@end
